package newWorldxxxTP02;

import java.io.*;

/**
 *  Cette classe repr&eacute;sente la race des Humains.
 *
 * @author P. Chaudeyrac
 */
public class Human extends LivingBeing implements Serializable {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Human(long date, String name) {
        super(date);
        this.name = name;
    }

    public String toString() {
        return "Human -> name: " + name + ", " + super.toString();
    }

    /* (non-Javadoc)
     * @see newWorldxxTP01.LivingBeingInterface#getLifespan()
     */
    public long getLifespan() {
        return humanLifespan;
    }
    /**
     * Cette variable definie la dur�e de vie des humains
     */
    static final long humanLifespan = 100;

    public void saveData(FileOutputStream flux) throws IOException
    {
        //creation d'un objet pour permettre de serialiser (sorte de filtre)
        ObjectOutputStream out = new ObjectOutputStream(flux);

        //on sauvegarde notre objet et on vide le tampon
        out.writeObject(this);
        out.flush();
    }

//    public void readData(FileInputStream flux) throws IOException {
//        ObjectInputStream input = new ObjectInputStream(flux);
//        
////        int i = input.readInt();
//
////        Human myHuman = (Human) input.readObject();
//        System.out.println("Human  id: " + myHuman.getName());
//        input.close();
//    }

    public static void main(String[] args) throws ClassNotFoundException {
        Human myHuman = new Human(0, "Sam");
        myHuman.setName("SupermanFou");
        System.out.println("Afficher propriétés d'un humain \n");
        System.out.println(myHuman.toString());
        try {
            // Ouvre le fichier ...
            FileOutputStream file = new FileOutputStream("save.dat");
            // SAv de l'objet
            myHuman.saveData(file);
            // vide le tanpom
            file.flush();
            //Fermeture
            file.close();
        } //Gestion des erreurs
        catch (IOException ioe) {
            System.out.println("Problème écriture");
        }
        
        try {
            
//            FileInputStream file = new FileInputStream("save.dat");
//            //lecture
//            myHuman.readData(file);
          
            FileInputStream file = new FileInputStream("save.dat");
            ObjectInputStream input = new ObjectInputStream(file);
            Human human = (Human) input.readObject();
            System.out.println("nom : "+human.getName());
            file.close();
            
        } catch (FileNotFoundException ioe) {
            System.out.println("fichier introuvable");
        } 
         catch (IOException ioe) {
            System.out.println("Problème lecture");
        }

    }
}
    
    
